package com.nokia.examplegame;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class PlayerSprite extends Sprite {

	public static final int HEIGHT = 63;

	public static final int WIDTH = 45;

	private static int[] FRAME_SEQUENCE = { 3, 2, 1, 2 };

	private int initialX;

	private int initialY;

	private int notJumping = -6;

	private int isJumping = notJumping;

	private int scoreDuringJump = 0;

	public PlayerSprite(Image image, int initialX, int initialY) {
		super(image, WIDTH, HEIGHT);
		this.initialX = initialX;
		this.initialY = initialY;
		defineReferencePixel(WIDTH / 2, 0);
		setRefPixelPosition(initialX, initialY);
		setFrameSequence(FRAME_SEQUENCE);
	}

	public void update(int tickCount, boolean left) {
		if (left) {
			setTransform(TRANS_MIRROR);
			move(-1, 0);
		} else {
			setTransform(TRANS_NONE);
			move(1, 0);
		}

		if (tickCount % 4 == 0) { // slow the animation down a little
			if (isJumping == notJumping) {
				nextFrame();
			} else {
				isJumping++;
				if (isJumping < 0) {
					setRefPixelPosition(getRefPixelX(), getRefPixelY()
							- (2 << (-isJumping)));
				} else {

					if (isJumping != -notJumping - 1) {
						setRefPixelPosition(getRefPixelX(), getRefPixelY()
								+ (2 << isJumping));
					} else {
						isJumping = notJumping;
						setRefPixelPosition(getRefPixelX(), initialY);
						setFrameSequence(FRAME_SEQUENCE);
						scoreDuringJump = 0;
					}
				}
			}
		}
	}

	public void jump() {
		if (isJumping == notJumping) {
			isJumping++;
			setFrameSequence(null);
			setFrame(0);
		}
	}

	public int increaseScoreThisJump() {
		if (scoreDuringJump == 0) {
			scoreDuringJump++;
		} else {
			scoreDuringJump *= 2;
		}
		return scoreDuringJump;
	}

	public int checkCollision(ObstacleSprite obstacle) {
		int returnValue = 0;
		boolean collided = collidesWith(obstacle, true);
		if (collided) {
			returnValue = 1;
			obstacle.reset();
		}
		return returnValue;
	}

	public void reset() {
		isJumping = notJumping;
		scoreDuringJump = 0;
		setRefPixelPosition(initialX, initialY);
		setFrameSequence(FRAME_SEQUENCE);
		setTransform(TRANS_NONE);
	}

}